package com.example.service;

import org.apache.curator.framework.recipes.queue.SimpleDistributedQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/****
 *
 * 简单MQ队列
 */
@Service
public class SimpleDistributedQueueServiceImpl implements SimpleDistributedQueueService, InitializingBean, DisposableBean {

    public static final String DISTRIBUTEDQUEUE = "/zookeeper/simple";

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private ZookeeperService zookeeperService;

    private SimpleDistributedQueue simpleDistributedQueue;

    private Thread thread;

    @Override
    public SimpleDistributedQueue getSimpleDistributedQueue() {
        return this.simpleDistributedQueue;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.simpleDistributedQueue = zookeeperService.getSimpleDistributedQueue(DISTRIBUTEDQUEUE);
        this.thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        byte[] take = simpleDistributedQueue.take();
                        logger.warn("SimpleDistributedQueueServiceImpl : " + new String(take));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        this.thread.start();
    }

    @Override
    public void destroy() throws Exception {
        if (this.thread.isAlive()) {
            this.thread.stop();
        }
    }
}
